<template>
  <div id="content">
    <globle-linear-border>
      <el-card class="searchBox">
        <el-form :inline="true">
          <el-form-item label="课程名称">
            <el-input v-model="pageQuery.otherParams.courseName" placeholder="输入课程名称搜索" clearable />
          </el-form-item>
          <el-form-item label="教师姓名">
            <el-input v-model="pageQuery.otherParams.tchName" placeholder="输入教师姓名搜索" clearable />
          </el-form-item>
          <el-form-item label="课程学年">
            <el-select v-model="pageQuery.otherParams.schoolYear" placeholder="选择学年搜索" clearable>
              <el-option v-for="item in schoolYearList" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="课程学期">
            <el-select v-model="pageQuery.otherParams.stage" placeholder="选择学期搜索" clearable>
              <el-option label="第一学期" value="1" />
              <el-option label="第二学期" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="年级">
            <el-input v-model="pageQuery.otherParams.grade" placeholder="输入年级搜索" clearable />
          </el-form-item>
          <el-form-item label="开课类型">
            <el-input v-model="pageQuery.otherParams.courseType" placeholder="输入开课类型搜索" clearable />
          </el-form-item>
          <el-form-item label="学时类型">
            <el-input v-model="pageQuery.otherParams.classHourType" placeholder="输入学时类型搜索" clearable />
          </el-form-item>
          <el-form-item label="是否删除">
            <el-select v-model="pageQuery.otherParams.courseIsDelete" placeholder="选择课程是否删除搜索" clearable>
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <section>
              <el-button type="success" @click.stop="onMoreCilck">高级筛选</el-button>
              <el-button type="primary" icon="Search" @click.stop="getPageInfo">搜 索</el-button>
              <el-button type="warning" icon="RefreshRight" @click.stop="reset">重 置</el-button>
              <el-button type="success" icon="Plus" @click="onAdd">添加课程</el-button>
              <el-button type="danger" icon="Minus" @click="onBatchDelete">批量删除</el-button>
              <el-upload ref="uploadRef" :action="api.course.fileImportUrl" :show-file-list="false"  
                :on-progress="onProgress" :on-success="onSuccess" accept=".xlsx" :limit="1" :headers="headers">
                <el-button type="warning" icon="Download">导入数据</el-button>
              </el-upload>
              <el-button type="warning" icon="Upload" @click="onExpose">导出数据</el-button>
            </section>
          </el-form-item>
        </el-form>

      </el-card>
    </globle-linear-border>

    <globle-linear-border style="margin-top: 20px">
      <el-card class="mainBox">
        <span v-if="tableData.rows">
          <el-table :border="true" stripe ref="tableRef" :data="tableData.rows" @selection-change="onSeleceChange"
            cell-class-name="table-cell" header-cell-class-name="table-header-cell">
            <el-table-column type="selection" width="55" />
            <el-table-column property="grade" label="年级" width="80" />
            <el-table-column property="schoolYear" label="学年" width="130" />
            <el-table-column property="stage" label="学期" width="100" />
            <el-table-column property="courseCode" label="课程代码" />
            <!-- <el-table-column property="courseName" label="课程名称" /> -->
            <el-table-column property="tchName" label="教师名称" />
            <el-table-column property="teachClass" label="教学班" width="150"/>
            <el-table-column property="week" label="周数" />
            <!-- <el-table-column property="weekDay" label="星期" />
            <el-table-column property="orderNum" label="序号" /> -->
            <!-- <el-table-column property="place" label="地点" width="140" show-overflow-tooltip /> -->
            <el-table-column property="classHourType" label="学时类型" />
            <el-table-column property="courseType" label="开课类型" width="100"/>
            <el-table-column property="stuClass" label="已选人数" width="80">
              <template #default="scope">{{ scope.row.selectedNum }}/{{ scope.row.maxPerson }}</template>
            </el-table-column>
            <!-- <el-table-column label="课程状态">
              <template #default="scope">
                <el-tag effect="dark" v-if="scope.row.courseIsBegin == 1" dark size="small" type="success">选课中</el-tag>
                <el-tag effect="dark" v-else size="small" dark type="danger">已停选</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="成绩录入">
              <template #default="scope">
                <el-tag effect="dark" v-if="scope.row.scoreIsBegin == 1" dark size="small" type="success">录入中</el-tag>
                <el-tag effect="dark" v-else size="small" dark type="danger">已停录</el-tag>
              </template>
            </el-table-column> -->
            <el-table-column label="课程颜色">
              <template #default="scope">
                <el-tag effect="dark" dark size="small" :color="scope.row.color" style="border-width: 0;"></el-tag>
              </template>
            </el-table-column>
            <el-table-column label="是否删除">
              <template #default="scope">
                <el-tag effect="dark" v-if="scope.row.isDelete == 0" dark size="small" type="success">未删除</el-tag>
                <el-tag effect="dark" v-else size="small" dark type="danger">已删除</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="260">
              <template #default="scope">
                <el-button type="primary" size="small" @click="onEdit(scope.row)">修改</el-button>
                <el-button v-if="scope.row.isDelete == 0" type="danger" size="small" @click="onDelete(scope.row)">删除</el-button>
                <el-button v-else type="warning" size="small" @click="onRecover(scope.row)">恢复</el-button>
                <el-button type="success" size="small" @click="onCheckStu(scope.row)">查看选课学生</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination v-model:currentPage="pageQuery.pageParams.pageNum"
            v-model:page-size="pageQuery.pageParams.pageSize" :page-sizes="pageSizeOption" :background="true"
            :small="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.totalSize"
            @size-change="onSizeChange" @current-change="onCurrentChange" />
        </span>
      </el-card>
    </globle-linear-border>
    <!-- 弹窗 -->
    <suspense>
      <dialog-vue ref="dialogRef" @onReGetData="getPageInfo" @onReSelect="onAdd"></dialog-vue>
    </suspense>
    <add-drawer ref="addRrawerRef" @on-select-tch="onSelectTch"></add-drawer>
    <more-params ref="moreParamsRef" @reload="reload"></more-params>
    <stu-drawer ref="stuDrawerRef"></stu-drawer>
    <export-dialog ref="exportDialogRef"></export-dialog>
  </div>
</template>

<script lang="ts" setup>
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, ElNotification, ElTable, UploadFile, UploadFiles } from 'element-plus';
import { ICoursePageParams, IPageRes, ICourse, APIData, ITch } from '../../../type';
import { useAPI } from '../../../request/api';
import AddDrawer from './components/AddDrawer.vue';
import MoreParams from './components/MoreParams.vue';
import StuDrawer from './components/StuDrawer.vue';
import ExportDialog from './components/ExportDialog.vue';
//注意!!定义动态引入组件时需要使用defineAsyncComponent，并且在template中需要搭配suspense组件使用,它是一个异步组件解决方案。
const DialogVue = defineAsyncComponent(() => import('./components/Dialog.vue'));

onMounted(() => {
  findAllCourseSchoolYear();
  getPageInfo();
});

const api = useAPI();
const uploadRef = ref();
const moreParamsRef = ref();
const dialogRef = ref();
const addRrawerRef = ref();
const stuDrawerRef = ref();
const exportDialogRef = ref();
let headers = {'token': localStorage.getItem('token')}
const tableRef = ref<InstanceType<typeof ElTable>>();
const schoolYearList = ref([] as { label:string; value:string }[]);

let deleteIdList = [] as Array<string>;
const pageSizeOption = [5, 10, 15, 20];
const pageQuery = reactive<ICoursePageParams>({
  otherParams: {
    courseName: '',
    tchName: '',
    schoolYear: '',
    stage: '',
    grade: '',
    courseType: '',
    classHourType: '',
    courseIsDelete: '',

    //以下在更多弹窗里面
    // courseCode: '',
    // openCollege: '',
    // place: '',
    // credit: '',
    // week: '',
    // weekDay: '',
    // orderNum: '',
    // teachClass: '',
    // totalHours: '',
    // allowBand: '',
    // workId: ''
    // studentId: '',
  },
  pageParams: {
    pageNum: 1,
    pageSize: pageSizeOption[1],
    sortField: '',
    sortType: '',
  },
});
const tableData = ref({} as IPageRes);

const reset = () => {
  pageQuery.otherParams = {
    courseName: '',
    tchName: '',
    schoolYear: '',
    stage: '',
    grade: '',
    courseType: '',
    classHourType: '',
    courseIsDelete: ''
  }
  pageQuery.pageParams = {
  pageNum: 1,
  pageSize: pageSizeOption[1],
  sortField: '',
  sortType: ''
}
  getPageInfo();
}

const onCheckStu = (row: ICourse) => {
  stuDrawerRef.value.open(row)
}

const onEdit = (row: ICourse) => {
  dialogRef.value.openDialogByEdit(row.id);
};

const onAdd = () => {
  addRrawerRef.value.openByAdd();
};

const onMoreCilck = () => {
  moreParamsRef.value.open();
}

const reload = (data: any) => {
  tableData.value = data;
}

const onDelete = (row: ICourse) => {
  ElMessageBox.confirm('您将该课程信息,确定继续吗?', '提示', { type: 'warning' })
    .then(() => {
      deleteIdList.push(row.id);
      deleteInfo();
    })
    .catch(() => { });
};

const onRecover = async (row: ICourse) => {
  // const params = JSON.parse(JSON.stringify(row));
  // params.isDelete = 0;
  const res: APIData = await api.course.recover({ courseId: row.id});
  if (res.code === 200) {
    getPageInfo();
    ElMessage.success('恢复成功');
  }
  else ElMessage.error(res.message);
}

const onSelectTch = (list: ITch[]) => {
  setTimeout(() => {
    dialogRef.value.openDialogByAdd(list);
  }, 300);
};

//上传进行
const onProgress = (evt: any, uploadFile: UploadFile) => {
  ElMessage.success(`${uploadFile.name}正在上传中`);
};
//上传成功
const onSuccess = (response: APIData, uploadFile: UploadFile) => {
  console.log('response',response);
  
  if (response.code == 200) {
    uploadRef.value.clearFiles();
    getPageInfo();
    ElMessage.success(`${uploadFile.name}上传成功`);
  } else {
    uploadRef.value.clearFiles();
    ElNotification.error({ title: `${response.message}`,message: `${response.data}` })
  }
};

//导出
const onExpose = () => {
  exportDialogRef.value.open();
};

//分页大小
const onSizeChange = (val: number) => {
  pageQuery.pageParams.pageSize = val;
  pageQuery.pageParams.pageNum = 1;
  getPageInfo();
};
//分页页码
const onCurrentChange = (val: number) => {
  pageQuery.pageParams.pageNum = val;
  getPageInfo();
};

//勾选(仅收集删除数据)
const onSeleceChange = (rowList: ICourse[]) => {
  deleteIdList = [] as Array<string>;
  rowList.forEach(item => {
    deleteIdList.push(item.id);
  });
};

//勾选删除
const onBatchDelete = () => {
  if (deleteIdList.length !== 0)
    ElMessageBox.confirm('您将删除勾选的课程信息,确定继续吗?', '提示', { type: 'warning' })
      .then(() => {
        deleteInfo();
      })
      .catch(() => { });
  else ElMessage.error('未勾选任何数据');
};

const findAllCourseSchoolYear = async () => {
  const res: APIData = await api.course.findAllCourseSchoolYear();
  if (res.code == 200) {
    const originList = res.data;
    schoolYearList.value = originList.map((item: string) => {
      return { label: `${item}学年`, value: `${item}` }
    })
  }
};

const getPageInfo = async () => {
  const res = await api.course.findPage(pageQuery);
  tableData.value = res.data;
};

const deleteInfo = async () => {
  const res = await api.course.delete(deleteIdList);
  if (res.data) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
    getPageInfo();
  }
};
</script>

<style lang="scss" scoped>
#content {
  height: 100%;
  padding:  14px 32px;
  // border: 2px solid red;

  .searchBox {
    &-item {
      margin-right: 10px;
    }

    // :deep(.el-form-item) {
    //   margin-bottom: 8px;
    // }

    :deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
    }

    section {
      display: flex;
    }

    :deep(.el-input__wrapper) {
      width: 200px;
    }
  }

  .mainBox {
    :deep(.el-checkbox__inner) {
      background-color: var(--main-color);
      transition: background 0.3s ease;
    }

    :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: var(--active-color);
      transition: background 0.3s ease;
    }
  }
}
</style>
